package controller;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.UserAccount;
import model.type.SubjectType;
import util.Log;
import validator.UserAccountValidator;
import web.JSONMessage;
import db.ImbiConnection;

public class UserManageController extends HttpServlet{

	private static final long serialVersionUID = 1L;
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		UserAccount u = (UserAccount)request.getSession().getAttribute("user");
		if(u != null){
			if(request.getParameter("delete")!= null){
				deleteUser(request, response, u);
			} else addUser(request, response, u);
		}	
		
	}
	private void deleteUser(HttpServletRequest request,
			HttpServletResponse response, UserAccount u) throws IOException {		
		try{
			int id = Integer.parseInt(request.getParameter("id"));		
			UserAccount user = ImbiConnection.getUserAccountDAO().find(id);
			if(user != null && u.getId() != user.getId()){
				ImbiConnection.getUserAccountDAO().delete(user);
				response.getWriter().write(JSONMessage.message("User deleted!"));
				Log.write(u.getUsername()+" deleted user "+user.getUsername());
			} else throw new NumberFormatException();
		} catch(NumberFormatException e){
			response.getWriter().write(JSONMessage.errorMessage("Invalid parameters"));
		}
	}
	private void addUser(HttpServletRequest request,
			HttpServletResponse response, UserAccount u)
			throws ServletException, IOException {
		UserAccountValidator validator = new UserAccountValidator(
			"0", 
			request.getParameter("employee"),
			"1",
			request.getParameter("valid_from"),
			request.getParameter("valid_to"),
			"1",
			request.getParameter("pass"),
			request.getParameter("user")
		);
		try{		
			if(validator.isValidNewUser()){
				ImbiConnection.getUserAccountDAO().insert(
					new UserAccount(
						0, 
						SubjectType.EMPLOYEE,
						validator.getSubject(),
						validator.getUser(),
						validator.getPass(),
						validator.getStatus(),
						validator.getValidFrom(),
						validator.getValidTo(),
						u.getEmployee().getId(),					 
						new Date(), 
						validator.getPasswordNeverExpires()
					)
				);
				Log.write(u.getUsername()+" added user "+validator.getUser());
			}
		} catch(IllegalArgumentException e){ /* User exists */ }
		
		request.setAttribute("users", ImbiConnection.getUserAccountDAO().findAll());
		request.setAttribute("employees", ImbiConnection.getEmployeeDAO().findAll());
		request.getRequestDispatcher("/WEB-INF/user.jsp").forward(request, response);
	}
	
}
